package controller

import (
	"database/sql"
	"fmt"
	"path/filepath"
	"strconv"
	"strings"

	"github.com/gin-gonic/gin"
	_ "github.com/mattn/go-sqlite3"
)

type RasterTileController struct {
	tileDataPath string
}

func NewRasterTileController(tileDataPath string) *RasterTileController {
	return &RasterTileController{tileDataPath: tileDataPath}
}

func (rtc *RasterTileController) GetTile(c *gin.Context) {
	rasterName := c.Param("rasterName")
	zStr := c.Param("z")
	xStr := c.Param("x")
	yStr := strings.Replace(c.Param("y"), ".png", "", 1)
	fmt.Println("GetTile:", rasterName, zStr, xStr, yStr)
	// Construct the full path to the SQLite database file
	dbPath := filepath.Join(rtc.tileDataPath, rasterName+".sqlite")

	// Open the database connection dynamically
	db, err := sql.Open("sqlite3", dbPath)
	if err != nil {
		c.JSON(500, gin.H{"error": fmt.Sprintf("Failed to open database %s: %v", dbPath, err)})
		return
	}
	defer db.Close()

	z, err := strconv.Atoi(zStr)
	if err != nil {
		c.JSON(400, gin.H{"error": "Invalid z parameter"})
		return
	}
	x, err := strconv.Atoi(xStr)
	if err != nil {
		c.JSON(400, gin.H{"error": "Invalid x parameter"})
		return
	}
	y, err := strconv.Atoi(yStr)
	if err != nil {
		c.JSON(400, gin.H{"error": "Invalid y parameter"})
		return
	}

	var tileID int
	query := `SELECT id FROM Tiles WHERE Zoom = ? AND X = ? AND Y = ?`
	err = db.QueryRow(query, z, x, y).Scan(&tileID)
	if err != nil {
		if err == sql.ErrNoRows {
			c.JSON(404, gin.H{"error": "Tile not found"})
		} else {
			c.JSON(500, gin.H{"error": fmt.Sprintf("Database query error: %v", err)})
		}
		return
	}

	var tileData []byte
	query = `SELECT Tile FROM TilesData WHERE id = ?`
	err = db.QueryRow(query, tileID).Scan(&tileData)
	if err != nil {
		if err == sql.ErrNoRows {
			c.JSON(404, gin.H{"error": "Tile data not found"})
		} else {
			c.JSON(500, gin.H{"error": fmt.Sprintf("Database query error: %v", err)})
		}
		return
	}

	c.Data(200, "image/png", tileData)
}
